package com.ruoyi.zsix.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.form.FormEntity;
import com.ruoyi.common.core.domain.form.FormSortEntity;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.zsix.domain.formComponents.FormDataValue;
import com.ruoyi.zsix.domain.taskAssignee.GenerWork;
import com.ruoyi.zsix.mapper.formComponentsMapper.FormEntityMapper;
import com.ruoyi.zsix.mapper.formComponentsMapper.FormSortEntityMapper;
import com.ruoyi.zsix.mapper.taskAssigneeMapper.GenerWorkMapper;
import com.ruoyi.zsix.service.IFormMapService;
import com.ruoyi.zsix.service.manager.IFormManager;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IFormMapServiceImpl implements IFormMapService {
    @Autowired
    private FormEntityMapper formEntityMapper;
    @Autowired
    private FormSortEntityMapper formSortEntityMapper;
    @Autowired
    private GenerWorkMapper generWorkMapper;
    @Autowired
    private IFormManager iFormManager;
    /**
     * 获取表单列表
     * @return
     */
    @Override
    public List<FormEntity> formList(FormEntity formInfo){
        List<FormEntity> formList = formEntityMapper.formList(formInfo.getName(),formInfo.getFormSort());
        return formList;
    }
    /**
     * 获取表单树
     * @return
     */
    @Override
    public List<FormEntity> getFormTree(){
        return formEntityMapper.getFormTree();
    }
    @Override
    public FormEntity getFormEntity(String id){
        try{
            FormEntity formEntity=formEntityMapper.formEntity(id);
            return formEntity;
        }
        catch (Exception ex){
            return new FormEntity();
        }
    }
    /**
     * 增加/修改表单
     * @param param
     * @return
     */
    @Override
    public String editForm(JSONObject param){
        JSONObject jsonObject=JSONObject.parseObject(param.getString("viewcode"));
        JSONObject configJson=JSONObject.parseObject(jsonObject.getString("config"));

        FormEntity formEntity=getFormEntity(param.getString("formid"));
        if(formEntity==null) {
            formEntity=new FormEntity();
            formEntity.setId(param.getString("formid"));
            formEntity.setName(configJson.getString("formRef"));
            formEntity.setCreateTime(DateTime.now().toString("yyyy-MM-dd hh:mm:ss"));
            formEntity.setFormSort(configJson.getString("formSort"));
            formEntity.setForm_data_table(configJson.getString("tableName"));
            formEntity.setForm_json(param.getString("viewcode"));

            iFormManager.addForm(formEntity);
        }
        else{
            formEntity.setForm_json(param.getString("viewcode"));
            iFormManager.updateForm(formEntity);
        }


        return "设置成功";
    }
    /**
     * 删除表单
     * @param id
     * @return
     */
    @Override
    public String deleteForm(String id){
        int i=formEntityMapper.deleteForm(id);
        return "执行成功";
    }
    /**
     * 获取表单分类列表
     * @return
     */
    @Override
    public List<FormSortEntity> formSortList(){
        try{
            List<FormSortEntity> formSortList=formSortEntityMapper.formSortList();
            //2、组装树形结构
            List<FormSortEntity> newList = formSortList.stream()
                    .filter(t -> t.getParentNo().equals("0") )
                    .map((menu) -> {
                        menu.setChildren(iFormManager.getChildren(menu,formSortList));
                        return menu;
                    })
                    .collect(Collectors.toList());
            return newList;
        }
        catch (Exception ex){
            return new ArrayList<>();
        }
    }
    /**
     * 增加表单分类
     * @param formSortEntity
     * @return
     */
    @Override
    public String addFormSort(FormSortEntity formSortEntity){
        formSortEntity.setId(UUID.randomUUID().toString());
        formSortEntityMapper.addFormSort(formSortEntity);
        return "执行成功";
    }

    /**
     * 修改表单分类
     * @param formSortEntity
     * @return
     */
    @Override
    public String updateFormSort(FormSortEntity formSortEntity){
        formSortEntityMapper.updateFormSort(formSortEntity);
        return "执行成功";
    }
    /**
     * 保存表单数据
     * @param formDataValue
     * @return
     */
    @Override
    public String saveFormDataJson(FormDataValue formDataValue){
        String guid=formDataValue.getId();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username=authentication.getName();
        try{
            GenerWork generWork=new GenerWork();
            if(!StringUtils.isEmpty(guid)&&!guid.equals("0")){
                generWork=generWorkMapper.generWork(guid);
                //如果为空，可能是外部表单传过来的businessKey
                if(generWork==null){
                    generWork=new GenerWork();
                    generWork.setId(guid);
                    if(formDataValue.getForm_type().equals("1")){
                        generWork.setMap_json(formDataValue.getForm_url());
                    }
                    else {
                        generWork.setMap_json(formDataValue.getMapJson());
                        generWork.setData_json(formDataValue.getDataJson());
                    }
                    generWork.setStarter(username);
                    generWork.setCreatetime(DateTime.now().toString("yyyy-MM-dd hh:mm:ss"));
                    generWork.setProcesskey(formDataValue.getProcessKey());
                    generWorkMapper.insertGenerWork(generWork);
                }
                else {
                    generWork.setId(guid);
                    if (formDataValue.getForm_type().equals("1")) {
                        generWork.setMap_json(formDataValue.getForm_url());
                    } else {
                        generWork.setMap_json(formDataValue.getMapJson());
                        generWork.setData_json(formDataValue.getDataJson());
                    }
                    generWork.setProcesskey(formDataValue.getProcessKey());
                    generWorkMapper.updateGenerWork(generWork);
                }
            }
            else {
                guid=UUID.randomUUID().toString();
                generWork.setId(guid);
                if(formDataValue.getForm_type().equals("1")){
                    generWork.setMap_json(formDataValue.getForm_url());
                }
                else {
                    generWork.setMap_json(formDataValue.getMapJson());
                    generWork.setData_json(formDataValue.getDataJson());
                }
                generWork.setProcesskey(formDataValue.getProcessKey());
                generWork.setStarter(username);
                generWork.setCreatetime(DateTime.now().toString("yyyy-MM-dd hh:mm:ss"));
                generWorkMapper.insertGenerWork(generWork);
            }
            return guid;
        }
        catch (Exception ex){
            return "error";
        }
    }
    /**
     * 删除表单分类
     * @param formSortEntity
     * @return
     */
    @Override
    public String deleteFormSort(FormSortEntity formSortEntity){
        int i= formSortEntityMapper.deleteFormSort(formSortEntity.getId());
        return "删除成功";
    }
}
